package com.nuaa.militaryqa.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nuaa.militaryqa.bean.WeaponBigCategory;
import com.nuaa.militaryqa.service.WeaponDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class WeaponDataController {

    @Autowired
    WeaponDataService weaponDataService;

    @PostMapping("/weapon/uploadWeaponBigCate")
    public String uploadNewWeaponBigCate(@RequestPart("BigCate")MultipartFile bigCate,
                                         Model model){
        InputStream inStream = null;
        BufferedReader bufReader = null;
        StringBuffer StrBuf = new StringBuffer();
        String str = "";
        JSONObject jsonObject;
        String weaponName = "", weaponBigCate = "";
        //中间使用map进行记录是为了去除重复的武器名
        Map<String,String> nameAndCategoryMap = new HashMap<>();
        List<WeaponBigCategory> waitInsertList = new ArrayList<WeaponBigCategory>();
        //检验上传的文件是否为空
        if(bigCate.isEmpty()){
            model.addAttribute("errorMsg","上传文件不能为空");
        }
        //将上传的json文件转换为输入流读取其中的内容
        try{
            inStream = bigCate.getInputStream();
            bufReader = new BufferedReader(new InputStreamReader(inStream));
            while((str = bufReader.readLine()) != null){
                jsonObject = JSONObject.parseObject(str);
                weaponName = (String) jsonObject.get("名称");
                weaponBigCate = (String) jsonObject.get("大类");
                nameAndCategoryMap.put(weaponName,weaponBigCate);
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
        finally {
            try{
                bufReader.close();
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }
        for(Map.Entry<String,String> nameAndCate : nameAndCategoryMap.entrySet()){
            weaponName = nameAndCate.getKey();
            weaponBigCate = nameAndCate.getValue();
            waitInsertList.add(new WeaponBigCategory(weaponName, weaponBigCate));
        }
        weaponDataService.insertWeaponBigCate(waitInsertList);
        return "redirect:/weapon/uploadFile";
    }
}
